var frnds = '';
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
	console.log(sender.tab ? "from a content script:" + sender.tab.url
			: "from the extension");
	// if (request.greeting == "hello")
	var query = JSON.stringify(request);
	console.log(request.sendAjax);
	if (query.search('friends') > -1) {
		setfriends(request);
	}
	if(query.search('sendAjax') > -1)
		{
		sendAjaxReq('https://localhost:8443/extensionY/rest/extension/storeTimeTaken',
			(request.sendAjax));
		}
	/*
	 * if(query.search('setUser')>-1) {setUser(request);}
	 * 
	 * if(query.search('getUser')>-1) {setfriends(request);}
	 */

	sendResponse({
		
		farewell : 'background ' + frnds
	});
});

function sendAjaxReq(url, data) {
	var req = createRequest(); // defined above
	// Create the callback:
	req.onreadystatechange = function() {
		if (req.readyState != 4)
			return; // Not there yet
		if (req.status != 201) {
			return;
		}
		if (req.status == 500) {
			alert("Some error Occured");
			return;
		}

		// Request successful, read the response
		var resp = req.responseText;
		// document.getElementById('yes').visibility="hidden;
		// document.getElementById('no').visibility=hidden;

		// ... and use it as needed by your app.

		return req.responseText;
	}
	req.open("POST", url, true);
	req.setRequestHeader("Content-Type", "application/json");
	req.send(data);
}
function setfriends(request) {
	var friendsJson = JSON.parse(request.data.replace('\\', ''));
	frnds = friendsJson.friends;
	console.log(frnds);

}
function setUser(request) {
	var friendsJson = JSON.parse(request.data.replace('\\', ''));
	frnds = friendsJson.friends;
	console.log(frnds);

}
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { 
    console.log('onRequest: ' + JSON.stringify(request)); 
    console.log(JSON.stringify(sender)); 
    sendResponse({
		farewell : JSON.stringify(request)
	});
  }); 